﻿using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using Microsoft.ApplicationBlocks.Data;

namespace Customs.Components.KDT
{
	public class CanBo : BaseClass
	{
		public bool CheckExistFromKDT(string tenDangNhap)
		{
			string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString_KDT"].ConnectionString;
			string query = "SELECT * FROM tblDCBHQ WHERE TenLogin = @TenDangNhap";

			SqlParameter[] parameters = new SqlParameter[1];
			parameters[0] = new SqlParameter("@TenDangNhap", SqlDbType.VarChar, 50);
			parameters[0].Value = tenDangNhap;

			SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, CommandType.Text, query, parameters);
			if (reader.Read())
			{
				return true;
			}
			return false;
		}

		public bool Create(string tenDangNhap, string hoTen, string maPhongBan, bool quyenQuanTri)
		{
			string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString_KDT"].ConnectionString;
			string query = "INSERT INTO tblDCBHQ VALUES(@TenDangNhap, @MatKhau, @PhongBan, @HoTen, @Salt, @IsAdmin)";

			SqlParameter[] parameters = new SqlParameter[6];
			parameters[0] = new SqlParameter("@TenDangNhap", SqlDbType.VarChar, 50);
			parameters[0].Value = tenDangNhap;

			string salt = this.createSalt(5);
			string salt_pass = string.Concat(tenDangNhap.ToUpper(), salt);

			parameters[1] = new SqlParameter("@MatKhau", SqlDbType.VarChar, 50);
			parameters[1].Value = FormsAuthentication.HashPasswordForStoringInConfigFile(salt_pass, "SHA1");

			parameters[2] = new SqlParameter("@PhongBan", SqlDbType.NVarChar, 80);
			parameters[2].Value = maPhongBan;

			parameters[3] = new SqlParameter("@HoTen", SqlDbType.NVarChar, 50);
			parameters[3].Value = hoTen;

			parameters[4] = new SqlParameter("@Salt", SqlDbType.VarChar, 10);
			parameters[4].Value = salt;

			parameters[5] = new SqlParameter("@IsAdmin", SqlDbType.Bit);
			parameters[5].Value = quyenQuanTri;

			int val = SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, query, parameters);

			if (val > 0)
			{
				return true;
			}
			return false;
		}
	}
}